//
//  YYEMoreInfoViewController.m
//  YuYingEDU
//
//  Created by 胡波 on 2018/1/2.
//  Copyright © 2018年 胡波. All rights reserved.
//

#import "YYEMoreInfoViewController.h"
#import "YYEMineViewController.h"
#import "YYEFillInfoTableViewCell.h"
#import "BRDatePickerView.h"
#import "BRStringPickerView.h"
#import "NSStringExt.h"
#import "BRTextField.h"
#import "NSDate+BRAdd.h"
#import "UIViewController+UIViewControllerExt.h"

@interface YYEMoreInfoViewController () <UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,ChoosePhotoDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

//@property (nonatomic,strong) UITextField *phoneTF;
//@property (nonatomic,strong) UITextField *nameTF;
//@property (nonatomic,strong) UITextField *cardTF;
//@property (nonatomic,strong) UIButton *confirmBtn;
//@property (nonatomic,strong) UIButton *passBtn;

@property (nonatomic,strong) YYEBaseTableView *tableView;
@property (nonatomic,strong) UIImageView *headerIV;
@property (nonatomic,strong) BRTextField *phoneTF;
@property (nonatomic,strong) BRTextField *nameTF;
@property (nonatomic,strong) BRTextField *cardTF;
@property (nonatomic,strong) BRTextField *birthTF;
@property (nonatomic,strong) BRTextField *generTF;
@property (nonatomic,strong) BRTextField *eduTF;

@end

@implementation YYEMoreInfoViewController

static NSString *infoCell = @"infoCell";
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = GeneralBackColor;
    
    self.title = @"完善资料";
    
    [self configUI];

}

- (void)configUI {

    [self.view addSubview:self.tableView];
    self.tableView.backgroundColor = GeneralBackColor;
    self.tableView.tableHeaderView = [self headerView];
    self.tableView.tableFooterView = [self footerView];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self.tableView registerClass:[YYEFillInfoTableViewCell class] forCellReuseIdentifier:infoCell];
    
    [self.tableView makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(UIEdgeInsetsZero);
    }];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    if (@available(iOS 11.0, *)) {
        UIScrollView.appearance.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentAlways;
    } else {
        // Fallback on earlier versions
    }
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    if (@available(iOS 11.0, *)) {
        UIScrollView.appearance.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        // Fallback on earlier versions
    }
    
}

// 确定
- (void)confirmClicked {
    
    if (self.cardTF.text.length < 1) {
        
        [self.view makeToast:@"请输入身份证号码"];
        
        
    }else if (self.nameTF.text.length < 1) {
        
        [self.view makeToast:@"请输入姓名"];

        
    } else {
        
        if (![NSString checkUserIDCard:self.cardTF.text]) {
            
            [self.view makeToast:@"非法身份证号"];
            return;

        }

        NSDictionary *dic = @{
                              @"name":self.nameTF.text,
                              @"username":self.phoneTF.text,
                              @"credid":self.cardTF.text,
                              @"birth":self.birthTF.text,
                              @"sex":self.generTF.text,
                              @"degree":self.eduTF.text,
                              @"token":[LoginModel shareLogin].token
                              };
        NSLog(@" %@ ",dic);
        [SVProgressHUD show];
        [AFNHelper post:WriteUserInfo parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {

            [formData appendPartWithFileData:UIImageJPEGRepresentation(self.headerIV.image, 0.3)
                                        name:@"img"
                                    fileName:@"header.png"
                                    mimeType:@"image/png"];
            
        } success:^(id responseObject) {
            
            NSLog(@"%@",responseObject);
            
            PersonModel *model = [PersonModel yy_modelWithJSON:responseObject[@"data"][@"userinfo"]];
            [InfoCache archiveObject:model toFile:Person];
            
            
            if ([responseObject[@"status"] isEqual:@1]) {
                [self passClicked];
            }
            [SVProgressHUD showWithStatus:responseObject[@"message"]];
            [SVProgressHUD dismiss];
            
        } faliure:^(id error) {
            
            NSLog(@"请求失败");
            [SVProgressHUD showWithStatus:ShowError];
            [SVProgressHUD dismissWithDelay:0.5];
            
        }];
    }

}

// 跳过
- (void)passClicked {
    
    for (UIViewController *temp in self.navigationController.viewControllers) {

        if ([temp isKindOfClass:[YYEMineViewController class]]) {
            {
                [self.navigationController popToViewController:temp animated:YES];
            }
        }

    }
    
}

- (YYEBaseTableView *)tableView {
    
    if (!_tableView) {
        _tableView = [[YYEBaseTableView alloc]initwithDelegate:self];
    }
    return _tableView;
    
}

- (UIView *)headerView {
    
    UIView *contentView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 10)];
    contentView.backgroundColor = GeneralBackColor;
    return contentView;
    
}

- (UIView *)footerView {
    
    UIView *contentView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 170)];

    UIButton *confirmBtn = [[UIButton alloc]init];
    [confirmBtn setTitle:@"确定" forState:UIControlStateNormal];
    [confirmBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [confirmBtn setBackgroundColor:GeneralBlueColor];
    [confirmBtn addTarget:self action:@selector(confirmClicked) forControlEvents:UIControlEventTouchUpInside];
    confirmBtn.layer.cornerRadius = 5;
    [contentView addSubview:confirmBtn];

    UIButton *passBtn = [[UIButton alloc]init];
    [passBtn setTitle:@"暂不填写，跳过" forState:UIControlStateNormal];
    [passBtn setTitleColor:LineColor forState:UIControlStateNormal];
    [passBtn addTarget:self action:@selector(passClicked) forControlEvents:UIControlEventTouchUpInside];
    passBtn.layer.borderColor = LineColor.CGColor;
    passBtn.layer.borderWidth = 0.5;
    passBtn.layer.cornerRadius = 5;
    [contentView addSubview:passBtn];
    
    [confirmBtn makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(contentView.left).offset(30);
        make.right.equalTo(contentView.right).offset(-30);
        make.top.equalTo(contentView.top).offset(44);
        make.height.equalTo(42);
    }];
    
    [passBtn makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(contentView.left).offset(30);
        make.right.equalTo(contentView.right).offset(-30);
        make.top.equalTo(confirmBtn.bottom).offset(12);
        make.height.equalTo(42);
    }];
    
    return contentView;
    
}

#pragma mark -- UITableview
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return 7;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    YYEFillInfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:infoCell];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSArray *names = @[@"头像",@"手机号",@"姓名",@"身份证",@"生日",@"性别",@"学历"];
    cell.nameLabel.text = names[indexPath.row];
    
    switch (indexPath.row) {
        case 0: {
            
            cell.rightIV.hidden = NO;
            cell.headerIV.hidden = NO;
            self.headerIV = cell.headerIV;
            cell.delegate = self;
            
        }
            break;
        case 1: {
            
//            cell.rightTF.placeholder = @"请输入手机号";
//            self.phoneTF = cell.rightTF;
            [self setupPhoneTF:cell];
        
        }
            break;
        case 2: {
            
//            cell.rightTF.placeholder = @"请输入姓名";
//            self.nameTF = cell.rightTF;
            [self setupNameTF:cell];
        }
            break;
        case 3: {
            
//            cell.rightTF.placeholder = @"请输入身份证号码";
//            self.cardTF = cell.rightTF;
            [self setupCardTF:cell];
        }
            break;
        case 4: {
            
//            cell.rightTF.placeholder = @"请选择生日";
//            self.birthTF = cell.rightTF;
            [self setupBirthdayTF:cell];
            
        }
            break;
        case 5: {
            
//            cell.rightTF.placeholder = @"请选择性别";
//            self.generTF = cell.rightTF;
            [self setupGeneralTF:cell];
            
        }
            break;
        case 6: {
            
//            cell.rightTF.placeholder = @"请选择学历";
//            self.eduTF = cell.rightTF;
            [self setupEduTF:cell];
            
        }
            break;
        default:
            break;
    }
    
    return cell;
    
}

- (BRTextField *)getTextField:(UITableViewCell *)cell {
    BRTextField *textField = [[BRTextField alloc]initWithFrame:CGRectMake(SCREEN_WIDTH - 214, 0, 200, 55)];
    textField.backgroundColor = [UIColor clearColor];
    textField.font = [UIFont systemFontOfSize:13];
    [textField setValue:[UIFont boldSystemFontOfSize:13] forKeyPath:@"_placeholderLabel.font"];
    textField.textAlignment = NSTextAlignmentRight;
    textField.textColor = [UIColor blackColor];
    textField.delegate = self;
    [cell.contentView addSubview:textField];
    return textField;
}

#pragma mark -- 手机号
- (void)setupPhoneTF:(UITableViewCell *)cell {
    
    if (!_phoneTF) {
        _phoneTF = [self getTextField:cell];
        _phoneTF.placeholder = @"请输入手机号码";
        _phoneTF.enabled = NO;
        _phoneTF.text = [LoginModel shareLogin].username;
    }
    
}

#pragma mark -- 姓名
- (void)setupNameTF:(UITableViewCell *)cell {
    
    if (!_nameTF) {
        _nameTF = [self getTextField:cell];
        _nameTF.placeholder = @"请输入姓名";

    }
    
}

- (void)setupCardTF:(UITableViewCell *)cell {
    
    if (!_cardTF) {
        _cardTF = [self getTextField:cell];
        _cardTF.placeholder = @"请输入身份证号码";

    }
    
}

#pragma mark - 出生日期 textField
- (void)setupBirthdayTF:(UITableViewCell *)cell {
    if (!_birthTF) {
        _birthTF = [self getTextField:cell];
        _birthTF.placeholder = @"请选择生日";
        __weak typeof(self) weakSelf = self;
        _birthTF.tapAcitonBlock = ^{
            [BRDatePickerView showDatePickerWithTitle:@"出生年月" dateType:UIDatePickerModeDate defaultSelValue:weakSelf.birthTF.text minDateStr:@"" maxDateStr:[NSDate currentDateString] isAutoSelect:YES resultBlock:^(NSString *selectValue) {
                weakSelf.birthTF.text = selectValue;
            }];
        };
    }
}

#pragma mark -- 性别
- (void)setupGeneralTF:(UITableViewCell *)cell {
    
    if (!_generTF) {
        _generTF = [self getTextField:cell];
        _generTF.placeholder = @"请选择性别";
        __weak typeof(self) weakSelf = self;
        _generTF.tapAcitonBlock = ^{
            [BRStringPickerView showStringPickerWithTitle:@"" dataSource:@[@"男", @"女"] defaultSelValue:@"男" isAutoSelect:YES resultBlock:^(id selectValue) {
                weakSelf.generTF.text = selectValue;
            }];
        };
    }
    
}

#pragma mark -- 学历
- (void)setupEduTF:(UITableViewCell *)cell {
    
    if (!_eduTF) {
        _eduTF = [self getTextField:cell];
        _eduTF.placeholder = @"请选择学历";
        __weak typeof(self) weakSelf = self;
        _eduTF.tapAcitonBlock = ^{
            [BRStringPickerView showStringPickerWithTitle:@"学历" dataSource:@[@"大专以下", @"大专", @"本科", @"硕士", @"博士", @"博士后"] defaultSelValue:@"本科" isAutoSelect:YES resultBlock:^(id selectValue) {
                weakSelf.eduTF.text = selectValue;
            }];
        };
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 0) {
        return 70;
    }else {
        return 55;
    }
    
}

#pragma mark -- choosePhoto
- (void)choosePhone {
    
    UIImagePickerController *pickerVC = [[UIImagePickerController alloc]init];
    pickerVC.delegate = self;
//    pickerVC.allowsEditing = NO;
    
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"手机拍摄" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
       
        pickerVC.sourceType = UIImagePickerControllerSourceTypeCamera;
//        pickerVC.cameraDevice = UIImagePickerControllerCameraDeviceFront;
        [self presentViewController:pickerVC animated:YES completion:nil];
        
    }];
    
    UIAlertAction *photosAction = [UIAlertAction actionWithTitle:@"相册选择" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        
        pickerVC.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:pickerVC animated:YES completion:nil];
        
    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        
        [alertVC addAction:cameraAction];
        
    }
    [alertVC addAction:photosAction];
    [alertVC addAction:cancelAction];
    [self presentViewController:alertVC animated:YES completion:nil];
    
}

#pragma mark -- UIImagepickerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    self.headerIV.image = image;
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

// 重写
- (void)back{
    
    [self popViewController:@"YYEMineViewController"];
}

@end
